


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;



import org.json.JSONObject;



public class SocketOp {
	private int REMOTE_PORT;
	private String REMOTE_IP;
	public SocketOp(String s_address,String s_port)
	{
		REMOTE_PORT = Integer.parseInt(s_port);
		REMOTE_IP = s_address;
	}
	public SocketOp()
	{
		REMOTE_IP="127.0.0.1";// default address = "127.0.0.1"
		REMOTE_PORT=20382;//default port = 20382
		try{
			BufferedReader  in = new BufferedReader(new FileReader("config.json"));
			String readMsg = in.readLine();
			while(in.ready())
				readMsg += in.readLine();
			in.close();
			JSONObject obj = new JSONObject(readMsg);
			String remote_ip = obj.getString("remote_ip");
			int remote_port = obj.getInt("remote_port");
			REMOTE_IP = remote_ip;
			REMOTE_PORT = remote_port;
		}catch(Exception e){
			
		}
	
	}
	public void setIp(String remote_ip){
		REMOTE_IP=remote_ip;
	}
	public void setPort(int remote_port){
		REMOTE_PORT=remote_port;
	}
	public String getIp(){
		return REMOTE_IP;
	}
	public int getPort(){
		return REMOTE_PORT;
	}
	public String request(String sendStr) throws Exception{
		String recvStr = null;
		Socket socket = null;
		BufferedReader in = null;
		PrintWriter out = null;
		try{
			socket = new Socket(REMOTE_IP,REMOTE_PORT);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream());
			out.print(sendStr);
			out.flush();
			recvStr = in.readLine();
		}catch(Exception e){
			throw e;
		}finally{
			try{
				in.close();		
				}catch(Exception e1){}
			try{ 
				out.close();		
				}catch(Exception e1){}
			try{ 
				socket.close();	
				}catch(Exception e1){}
		}
		return recvStr;
	}
}
